package com.example.demo.web.common.filter;

import com.example.demo.web.common.model.Ret;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.validation.ValidatorException;

/**
 * @author airhead
 */
@Slf4j
@Component(tag = "adminApi", delivered = false, index = -1)
public class AdminExceptionFilter implements Filter {
  @Override
  public void doFilter(Context ctx, FilterChain chain) throws Throwable {
    try {
      chain.doFilter(ctx);
    } catch (ValidatorException e) {
      log.error("validator exception", e);

      ctx.status(e.getCode());
      ctx.outputAsJson(Ret.fail(e.getMessage()).toJson());
    } catch (Throwable e) {
      log.error("other throwable", e);

      ctx.status(500);
      ctx.outputAsJson(Ret.fail(e.getMessage()).toJson());
    } finally {
      // 文件清理放此处也算合理，异常时需要清理和尝试恢复
      if (ctx.isMultipartFormData()) {
        try {
          ctx.filesDelete();
        } catch (IOException e) {
          log.error("clean temp file exception", e);
        }
      }
    }
  }
}
